﻿using FastJSON;
using FineAdmin.Common;
using FineAdmin.IService;
using FineAdmin.Model;
using FineAdmin.Service;
using HuiJI.Tools.TBK;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.UI.WebControls;

namespace FineAdmin.Web.Controllers
{
    public class MobileController : BaseMobileController
    {
        // GET: Mobile


        public IAppBarService AppBarService { get; set; }
        public IMaterialGoodsService MaterialGoodsService { get; set; }
        public IPostCategoryService PostCategoryService { get; set; }
        public IMaterialService MaterialService { get; set; }

        public ITipSubmitService TipSubmitService { get; set; }

        public ActionResult Index()
        {
           
            ViewBag.MCode = "tip";
            var PostCategoryList = PostCategoryService.GetAll();
            ViewBag.PostCategoryList = PostCategoryList;

            //ViewBag.NewestTime = PostsService.GetByWhere("where State=1", null, "top(1) * ", "order by Id desc").First().UpdateTime;
            return View();
        }

        [HttpPost]
        public ActionResult List(PostsModel model, PageInfo pageInfo, string code = "0")
        {
            var PostCategoryList = PostCategoryService.GetAll();
            pageInfo.field = "Id";
            pageInfo.order = "desc";
            if (!string.IsNullOrWhiteSpace(code) && code != "0")
            {
                model.Post_Type = PostCategoryList.Where(m => m.Code == code).First().Id;
            }
            model.State = 1;
            var result = PostsService.GetListByFilter(model, pageInfo);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 收藏
        /// </summary>
        /// <returns></returns>
        public ActionResult Collect()
        {

            return View();
        }

        public ActionResult PostsDetails(int id)
        {
            var posts = PostsService.GetById(id);
            //posts.Clicks += 1;
            PostsService.AddClicks(id);
            return View(posts);
        }

        [HttpPost]
        public ActionResult PostsLikeAdd(int id)
        {

            //var posts = PostsService.GetById(id);
            //posts.Likes += 1;
            if (!HuiJIRedisService.LikeOrTrampleExists(Session.SessionID, 1))
            {
                PostsService.AddLikes(id);
                HuiJIRedisService.LikeOrTrampleSet(Session.SessionID, 1);
                return Json(new AjaxResult { state = ResultType.success.ToString(), message = "OK" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new AjaxResult { state = ResultType.error.ToString(), message = "66秒内只能点一次赞" }, JsonRequestBehavior.AllowGet);
            }

        }

        [HttpPost]
        public ActionResult PostsTrampleAdd(int id)
        {

            if (!HuiJIRedisService.LikeOrTrampleExists(Session.SessionID, 2))
            {
                PostsService.AddTrample(id);
                HuiJIRedisService.LikeOrTrampleSet(Session.SessionID, 2);
                return Json(new AjaxResult { state = ResultType.success.ToString(), message = "OK" }, JsonRequestBehavior.AllowGet);
            }
            else
            {

                return Json(new AjaxResult { state = ResultType.error.ToString(), message = "66秒内只能点一次踩" }, JsonRequestBehavior.AllowGet);
            }


        }


        public ActionResult Nine()
        {
            ViewBag.MCode = "nine";
            return View();
        }

        public ActionResult AjaxNine(MaterialGoodsModel model, PageInfo pageInfo)
        {
            pageInfo.field = "Id";
            pageInfo.order = "desc";
            pageInfo.distinct = "ItemId";
            model.B_Price = 10;
            model.S_Price = 1;
            //var result = MaterialGoodsService.GetListByFilter(model, pageInfo);
            var result = MaterialGoodsService.GetDistinctListByFilter(model, pageInfo);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetImg(string c)
        {

            int height = int.Parse(c.Split('x')[0].ToString());
            int width = int.Parse(c.Split('x')[1].ToString());

            Bitmap bmp = new Bitmap(width, height);

            Graphics g = Graphics.FromImage(bmp);

            g.Clear(Color.Blue);

            g.FillRectangle(Brushes.Red, 2, 2, 65, 31);

            g.DrawString("学习MVC", new Font("黑体", 15f), Brushes.Yellow, new PointF(5f, 5f));

            MemoryStream ms = new MemoryStream();

            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            g.Dispose();

            bmp.Dispose();

            return File(ms.ToArray(), "image/jpeg");
        }


        public ActionResult GoodsDetails(int Id, string itemId = "")
        {
            ViewBag.isTKL = false;
            //RedisHelper rhelper = new RedisHelper(1);
            //var isCache = false;
            MaterialGoodsModel goods = new MaterialGoodsModel();
            var itemObject = HuiJIRedisService.MaterialGoodsGet("-1", itemId);//rhelper.StringGet("item:" + "M" + "-1" + ":ItemID" + itemId);//CacheHelper.GetCache("tbk_q_" + itemId);
            if (!string.IsNullOrWhiteSpace(itemObject))
            {
                goods = JSON.ToObject<MaterialGoodsModel>(itemObject);//itemObject as MaterialGoodsModel;

                if (goods != null)
                {
                    if (string.IsNullOrWhiteSpace(goods.TKL))
                    {

                        var url = !string.IsNullOrWhiteSpace(goods.CouponShareUrl) ? goods.CouponShareUrl : !string.IsNullOrWhiteSpace(goods.ClickUrl) ? goods.ClickUrl : "";

                        OpRecordService.AddOpRecord("淘口令", "淘宝客API", 1);
                        var tklObj = tbkTools.TKL(DefaultAdZone.TBK_AppKey, DefaultAdZone.TBK_AppSecret, url, "huiji", goods.Title);

                        if (tklObj.IsError == false)
                        {
                            goods.TKL = tklObj.Data.Model;

                            //CacheHelper.SetCache("tbk_q_" + itemId, goods, DateTime.Now.AddMinutes(30), TimeSpan.Zero);
                            //rhelper.StringSet("item:" + "M" + "-1" + ":ItemID" + itemId, JSON.ToJSON(goods), TimeSpan.FromMinutes(30));
                            HuiJIRedisService.MaterialGoodsSet(goods);

                            ViewBag.isTKL = true;
                        }
                        else
                        {
                            ViewBag.isTKL = false;
                        }
                    }
                    else
                    {
                        ViewBag.isTKL = true;
                    }
                    return View(goods);
                }
            }

            goods = MaterialGoodsService.GetById(Id);

            if (string.IsNullOrWhiteSpace(goods.TKL))
            {

                var url = !string.IsNullOrWhiteSpace(goods.CouponShareUrl) ? goods.CouponShareUrl : !string.IsNullOrWhiteSpace(goods.ClickUrl) ? goods.ClickUrl : "";
                OpRecordService.AddOpRecord("淘口令", "淘宝客API", 1);
                var tklObj = tbkTools.TKL(DefaultAdZone.TBK_AppKey, DefaultAdZone.TBK_AppSecret, url, "huiji", goods.Title);

                if (tklObj.IsError == false)
                {
                    goods.TKL = tklObj.Data.Model;

                    MaterialGoodsService.UpdateById(goods);

                    ViewBag.isTKL = true;
                }
                else
                {
                    ViewBag.isTKL = false;
                }
            }
            else {
                ViewBag.isTKL = false;
            }

            //goods.CouponStartTime = GetTime(goods.CouponStartTime).ToString("yyyy.MM.dd");
            //goods.CouponEndTime = GetTime(goods.CouponEndTime).ToString("yyyy.MM.dd");


            return View(goods);
        }
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }


        public ActionResult Subject()
        {
            ViewBag.MCode = "subject";
            ViewBag.AppBar = AppBarService.GetAll();
            return View();
        }

        public ActionResult SubjecShow(int id)
        {

            var appbar = AppBarService.GetById(id);

            ViewBag.Title = appbar.ShortName;

            var MaterialList = MaterialService.GetAll();
            //展现形式 一种 url 直达 一种 分类浏览

            if (!string.IsNullOrWhiteSpace(appbar.Mv2))
            {
                var definite = MaterialList.Where(m => m.CategoryV2 == appbar.Mv2).ToList();
                ViewBag.MaterialNav = definite;
            }

            if (!string.IsNullOrWhiteSpace(appbar.Mv3))
            {
                var definite = MaterialList.Where(m => m.CategoryV3 == appbar.Mv3).ToList();
                ViewBag.MaterialNav = definite;
            }

            if (string.IsNullOrWhiteSpace(appbar.Mv3) && string.IsNullOrWhiteSpace(appbar.Mv2))
            {

                return Redirect(appbar.LinkMobile_To);

            }

            return View();
        }

        public ActionResult AjaxMaterialGoods(MaterialGoodsModel model, PageInfo pageInfo)
        {
            pageInfo.field = "Id";
            pageInfo.order = "desc";
            var result = MaterialGoodsService.GetListByFilter(model, pageInfo);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult More()
        {
            ViewBag.MCode = "more";
            return View();
        }

        public ActionResult AjaxMore(MaterialGoodsModel model, PageInfo pageInfo, int pageOffset = 0)
        {


            pageInfo.field = "Id";
            pageInfo.order = "desc";
            model.Volume = 999;

            var result = MaterialGoodsService.GetListByFilter(model, pageInfo);
            //string count = result.GetType().GetProperty("count").GetValue(result).ToString();//拿到总数 
            //List<FineAdmin.Model.MaterialGoodsModel> data = result.GetType().GetProperty("data").GetValue(result);

            //// 通过搜索拿到数据
            //if (count == "0" || data.Count() == 0)
            //{

            //}

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AjaxMaterialOptional(MaterialGoodsModel model, PageInfo pageInfo, int pageOffset)
        {
            //RedisHelper rhelper = new RedisHelper(1);

            //进入物料精选搜索

            var ret = tbkTools.MaterialOptional(DefaultAdZone.TBK_AppKey, DefaultAdZone.TBK_AppSecret, (long)DefaultAdZone.TBK_AdzoneId, pageInfo.page - pageOffset, pageInfo.limit, model.Title, "total_sales_des", null, null);

            List<FineAdmin.Model.MaterialGoodsModel> data2 = new List<MaterialGoodsModel>();
            for (int i = 0; i < ret.ResultList.Count; i++)
            {
                MaterialGoodsModel mgm = new MaterialGoodsModel();

                mgm.CouponAfterPrice = ret.ResultList[i].ZkFinalPrice.ToDecimal(2) - ret.ResultList[i].CouponAmount.ToDecimal(2);
                mgm.ZkFinalPrice = ret.ResultList[i].ZkFinalPrice.ToDecimal(2);
                mgm.CouponAmount = ret.ResultList[i].CouponAmount.ToInt();
                mgm.CouponStartTime = ret.ResultList[i].CouponStartTime.ToDate();
                mgm.CouponEndTime = ret.ResultList[i].CouponEndTime.ToDate();
                mgm.SmallImages = JSON.ToJSON(ret.ResultList[i].SmallImages);
                mgm.PictUrl = ret.ResultList[i].PictUrl;
                mgm.ClickUrl = ret.ResultList[i].Url;
                mgm.CouponShareUrl = ret.ResultList[i].CouponShareUrl;
                mgm.Title = ret.ResultList[i].Title;
                mgm.ShopTitle = ret.ResultList[i].ShopTitle;
                mgm.ShortTitle = ret.ResultList[i].ShortTitle;
                mgm.ItemDescription = ret.ResultList[i].ItemDescription;
                mgm.ItemId = ret.ResultList[i].ItemId.ToString();
                mgm.Volume = ret.ResultList[i].Volume.ToInt();
                mgm.ReservePrice = ret.ResultList[i].ReservePrice;
                mgm.UserType = ret.ResultList[i].UserType.ToInt();
                mgm.CouponTotalCount = ret.ResultList[i].CouponTotalCount.ToInt();
                mgm.CouponRemainCount = ret.ResultList[i].CouponRemainCount.ToInt();
                mgm.ShopDsr = ret.ResultList[i].ShopDsr.ToInt();
                mgm.Mid = -1;//表示临时数据
                //CacheHelper.SetCache("tbk_q_" + mgm.ItemId, mgm, DateTime.Now.AddMinutes(30), TimeSpan.Zero);

                //rhelper.StringSet("item:" + "M" + "Q" + ":ItemID" + mgm.ItemId, JSON.ToJSON(mgm), TimeSpan.FromMinutes(30));

                HuiJIRedisService.MaterialGoodsSet(mgm);

                data2.Add(mgm);
            }

            return Json(new { code = 0, count = ret.TotalResults, data = data2, msg = "", pageOffset = pageInfo.page + 1 }, JsonRequestBehavior.AllowGet);
        }


        public ActionResult SubmitTip() { 
            
            return View(); 
        }

        public ActionResult AjaxSubmitTip(string captcha, TipSubmitModel ts) {

            if (Session["session_submitcode"].IsEmpty() || Md5.md5(captcha.ToLower(), 16) != Session["session_submitcode"].ToString())
            {
                //throw new Exception("验证码错误");
                return Json(ErrorTip("验证码错误"),JsonRequestBehavior.DenyGet);
            }

            ts.UpdateTime = DateTime.Now;
            ts.CreateTime = DateTime.Now;
            ts.CreateUserId = 1;
            ts.UpdateUserId = 1;
            ts.State = 0;
            ts.Ip = Net.Ip;

            if (!TipSubmitService.Insert(ts)) {

                return Json(ErrorTip("请重试！"), JsonRequestBehavior.DenyGet);
            }

            return Json(SuccessTip("提交成功"), JsonRequestBehavior.DenyGet);
        }

        public ActionResult GetSubmitCode() {

            return File(new VerifyCode().GetVerifyCode(type:2), @"image/Gif");
        }
    }
}